package com.xhx.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Function;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;

/**
 * pdf抽象处理类
 * 
 * @author xhx
 */
public abstract class AbstractPdfController {

	protected org.slf4j.Logger log;

	public AbstractPdfController(Logger log) {
		super();
		this.log = log;
	}

	protected <R> R processPdf(InputStream inpustStream, Function<PDDocument, R> func,
			Function<IOException, R> errorFunc) {
		try (PDDocument document = Loader.loadPDF(IOUtils.toByteArray(inpustStream))) {
			return func.apply(document);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return errorFunc.apply(e);
		}
	}

	protected <R> R processPdf(MultipartFile file, Function<PDDocument, R> func, Function<IOException, R> errorFunc) {
		try (PDDocument document = Loader.loadPDF(IOUtils.toByteArray(file.getInputStream()))) {
			return func.apply(document);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return errorFunc.apply(e);
		}
	}

	protected <R> R processPdf(File file, Function<PDDocument, R> func, Function<IOException, R> errorFunc) {
		try (PDDocument document = buildDocument(file)) {
			return func.apply(document);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return errorFunc.apply(e);
		}
	}

	protected PDDocument buildDocument(File file) throws IOException {
		return Loader.loadPDF(file);
	}

	protected PDDocument buildDocument(MultipartFile file) throws IOException {
		return Loader.loadPDF(IOUtils.toByteArray(file.getInputStream()));
	}

}
